package com.sinoglobal.dumping.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.sinoglobal.dumping.R;
import com.sinoglobal.dumping.api.Dumpling_RemoteImpl;
import com.sinoglobal.dumping.base.Dumpling_ShareAbstractActivity;
import com.sinoglobal.dumping.base.Dumpling_SharedPreferenceUtil;
import com.sinoglobal.dumping.base.Dumpling_SinoAsyncTask;
import com.sinoglobal.dumping.base.Dumpling_SinoConfig;
import com.sinoglobal.dumping.base.Dumpling_SinoConstans;
import com.sinoglobal.dumping.bean.Dumpling_BaseVo;
import com.sinoglobal.dumping.bean.Dumpling_NewCardVo;
import com.sinoglobal.dumping.util.Dumpling_FileUtils;
import com.sinoglobal.dumping.util.Dumpling_HttpMethodSet;
import com.sinoglobal.dumping.view.Dumpling_CancelSendDumplingsDialog;
import com.sinoglobal.wallet.util.LogUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.Random;

public class Dumpling_CongratulationCardActivity extends Dumpling_ShareAbstractActivity {

    public static final int UPLOAD_IMAGE_CODE = 11;
    private static final int SELECT_PHOTO_COMPLETE = 10;
    private static final String TAG = "Xs3AndroidDemo1";
    private String shareUrl;
    private String shareContent;
    private String shareTitle;
    private String sharePicUrl;
    private boolean exists = true;
    private boolean checked = true;
    private ImageView cardPhoto;
    private ImageView share;
    private Button cardRefresh;
    private EditText editText;
    private Button cardSend;
    private int imageWidth;
    private int imageHeight;
    private Uri resultImage;
    private String sendType;
    private ArrayList<String> blessing;
    private Random random = new Random();
    private Dumpling_CancelSendDumplingsDialog cancelDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTemplateTitleText.setText("包饺子");
        share = getView(R.id.title_right_btn_share);
        hideViewForGone(share, mTemplateRightImg);
        setContentView(R.layout.dumpling_activity_congratulation_card);
        Dumpling_FileUtils.imageFileName = null;//每次进入重置图片地址
        sendType = getIntent().getStringExtra("sendType");
        initView();
    }

    private void initView() {
        cardPhoto = (ImageView) findViewById(R.id.dumpling_card_photo);
        cardRefresh = (Button) findViewById(R.id.dumpling_card_refresh);
        editText = (EditText) findViewById(R.id.dumpling_card_congratulation);
        cardSend = (Button) findViewById(R.id.dumpling_card_send);
        cardPhoto.setOnClickListener(this);
        cardRefresh.setOnClickListener(this);
        cardSend.setOnClickListener(this);
        cardPhoto.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                imageWidth = cardPhoto.getWidth();
                imageHeight = cardPhoto.getHeight();
            }
        });
        editText.addTextChangedListener(new TextWatcher() {
            String beforeString;

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                beforeString = charSequence.toString();
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (editText.getLineCount() > 2) {
                    editText.setText(beforeString);
                    Toast.makeText(Dumpling_CongratulationCardActivity.this, "内容不能超过2行", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        mTemplateLeftImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog();
            }
        });
    }

    @Override
    public void onAntiViolence(View view) {
        if (R.id.dumpling_card_photo == view.getId()) {
            Intent intent = new Intent(Dumpling_CongratulationCardActivity.this, Dumpling_PhotosSelectorActivity.class);
            intent.putExtra("imageWidth", imageWidth);
            intent.putExtra("imageHeight", imageHeight);
            startActivityForResult(intent, SELECT_PHOTO_COMPLETE);
        } else if (R.id.dumpling_card_refresh == view.getId()) {
            if (blessing != null) {
                editText.setText(blessing.get(random.nextInt(blessing.size())));
            } else {
                getBlessing();
            }
        } else if (R.id.dumpling_card_send == view.getId()) {
            sendPictures();
        }
    }

    private void getBlessing() {
        new Dumpling_SinoAsyncTask<Void, Void, ArrayList<String>>(Dumpling_CongratulationCardActivity.this) {

            @Override
            public ArrayList<String> before(Void... params) throws Exception {
                return Dumpling_RemoteImpl.getInstance().getBlessing();
            }

            @Override
            public void after(ArrayList<String> strings) {
                if (strings != null) {
                    blessing = strings;
                    editText.setText(blessing.get(random.nextInt(blessing.size())));
                }
            }

            @Override
            public void exception() {

            }
        }.execute();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e(TAG, "onActivityResult requestCode:" + requestCode + ",resultCode:" + resultCode);
        if (SELECT_PHOTO_COMPLETE == requestCode && data != null) {
            Dumpling_SharedPreferenceUtil.put(this, "uploadFlag", false);//更换图片时将图片上传标志设置为flase
            resultImage = data.getData();
            if (resultImage != null) {
                Log.e("resultImage", data.getData().toString() + "-----" + data.getData().getPath());
                Picasso.with(Dumpling_CongratulationCardActivity.this)
                        .load(resultImage)
                        .placeholder(R.drawable.dumpling_card_photo_changeable_default)
                        .error(R.drawable.dumpling_card_photo_changeable_default)
                        .resize(imageWidth, imageHeight)
                        .centerCrop()
                        .into(cardPhoto);
            }
        } else if (UPLOAD_IMAGE_CODE == requestCode) {//add 2016.03.09
            saveCardInfo(Dumpling_FileUtils.imageFileName);
            Log.e("saveCardInfo", "saveCardInfo  onActivityResult");
        }
    }

    private void sendPictures() {
        Log.e(TAG, "resultImage:" + resultImage);
        if (resultImage == null) {
            saveCardInfo("FixedPicture/LJHYear/RetrG/578441yeargert89.png");
            Log.e("saveCardInfo", "saveCardInfo  sendPictures1");
        } else {
            if (!checked) {
                Toast.makeText(getApplicationContext(), "Please wait a moment...",
                        Toast.LENGTH_SHORT).show();
            } else if (!exists) {
                Toast.makeText(getApplicationContext(), "没找到服务",
                        Toast.LENGTH_SHORT).show();
            } else {
                boolean uploadFlag = (Boolean)Dumpling_SharedPreferenceUtil.get(this, "uploadFlag", false);
                Log.e(TAG, "uploadFlag:"+uploadFlag);//判断该图片是否在云上
                if (!uploadFlag) {
                    upload(resultImage);
                } else {
                    saveCardInfo(Dumpling_FileUtils.imageFileName);
                    Log.e("saveCardInfo", "saveCardInfo  sendPictures2");
                }
            }
        }
    }

    private void upload(Uri uri) {
        Log.e(TAG, "uploadUri:" + uri.toString());
        Intent it = new Intent(this, ProxyActivity.class);
        String path = Environment.getExternalStorageDirectory() + "/DynamicLoadHost/pluginb-debug.zip";
        it.putExtra(ProxyActivity.EXTRA_DEX_PATH, path);
        it.putExtra(ProxyActivity.EXTRA_URL, uri.toString());
        startActivityForResult(it, UPLOAD_IMAGE_CODE);
    }

    private void saveCardInfo(final String imagPath) {
        final String saveString = editText.getEditableText().toString();
        if (TextUtils.isEmpty(saveString)) {
            showToast("请输入祝福语");
        } else {
            new Dumpling_SinoAsyncTask<Void, Void, Dumpling_BaseVo>(Dumpling_CongratulationCardActivity.this) {

                @Override
                public Dumpling_BaseVo before(Void... params) throws Exception {
                    return Dumpling_RemoteImpl.getInstance().saveCard(imagPath, saveString, sendType);
                }

                @Override
                public void after(Dumpling_BaseVo dumpling_baseVo) {
                    if (dumpling_baseVo != null) {
                        if (100 == dumpling_baseVo.getCode()) {
                            sendCardInfo(imagPath);
                        }
                    } else {
                        Toast.makeText(Dumpling_CongratulationCardActivity.this, "访问网络失败", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void exception() {
                    Toast.makeText(Dumpling_CongratulationCardActivity.this, "访问网络失败", Toast.LENGTH_SHORT).show();
                }
            }.execute();
        }
    }

    private void sendCardInfo(final String imagPath) {
        new Dumpling_SinoAsyncTask<Void, Void, Dumpling_NewCardVo>(Dumpling_CongratulationCardActivity.this) {

            @Override
            public Dumpling_NewCardVo before(Void... params) throws Exception {
                return Dumpling_RemoteImpl.getInstance().newCard(imagPath, editText.getEditableText().toString(), sendType);
            }

            @Override
            public void after(Dumpling_NewCardVo dumpling_newCardVo) {
                if (dumpling_newCardVo != null) {
                    //分享贺卡
                    initShareData(dumpling_newCardVo);
                } else {
                    Toast.makeText(Dumpling_CongratulationCardActivity.this, "访问网络失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void exception() {
                Toast.makeText(Dumpling_CongratulationCardActivity.this, "访问网络失败", Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }

    private void initShareData(Dumpling_NewCardVo dumpling_newCardVo) {
        if (Dumpling_SinoConfig.sCardShare == null) {
            showToast("访问网络失败，请稍后再试");
            Dumpling_HttpMethodSet.getShareContent(Dumpling_CongratulationCardActivity.this,  "10007", "", "", "", "");
            goIntent(Dumpling_MainActivity.class);
        } else {
            shareUrl = Dumpling_SinoConfig.sCardShare.getResultList().getUrl() + "?name=" + Dumpling_SinoConstans.USER_NAME + "&productCode=" + Dumpling_SinoConstans.PRODUCT_CODE + "&pannikin_id=" + dumpling_newCardVo.getDumplingUserPutcardId();
            shareContent = Dumpling_SinoConfig.sCardShare.getResultList().getContent();
            shareTitle = Dumpling_SinoConfig.sCardShare.getResultList().getTitle();
            sharePicUrl = Dumpling_SinoConfig.sCardShare.getResultList().getPicurl();
            if (!shareUrl.contains("http://")) {
                shareUrl = "http://" + shareUrl;
            }
            LogUtils.e("shareUrl:" + shareUrl);
            shareCard();
        }
    }

    private void shareCard() {
        if ("1".equals(sendType)) {
            setShare(shareContent, shareTitle, null, shareUrl, 0, sharePicUrl);
        } else if ("2".equals(sendType)) {
            Intent intent = new Intent(Dumpling_CongratulationCardActivity.this, Dumpling_SendCardCompleteActivity.class);
            intent.putExtra("shareContent", shareContent);
            intent.putExtra("shareTitle", shareTitle);
            intent.putExtra("shareUrl", shareUrl);
            intent.putExtra("sharePicUrl", sharePicUrl);
            startActivity(intent);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy");
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showDialog();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showDialog() {
        if (cancelDialog == null) {
            cancelDialog = new Dumpling_CancelSendDumplingsDialog(this);
        }
        if (!cancelDialog.isShowing()) {
            cancelDialog.show();
        }
    }
}
